import babelpolyfill from 'babel-polyfill'
import Vue from 'vue'
import App from './App'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import 'main.css'
// import 'element-ui/lib/theme-default/index.css'
//import './assets/theme/theme-green/index.css'
import VueRouter from 'vue-router'
import store from './vuex/store'
import Vuex from 'vuex'
//import NProgress from 'nprogress'
//import 'nprogress/nprogress.css'
import routes from './routes'
// import Mock from './mock'
// Mock.bootstrap();
import 'font-awesome/css/font-awesome.min.css'
//自己的样式
//import '../src/styles/page.css'
import axios from 'axios'
//配置axios的全局基本路径
axios.defaults.baseURL='http://localhost:11000/ymcc';
//全局属性配置，在任意组件内可以使用this.$http获取axios对象
Vue.prototype.$http = axios

import PartUpload from 'upload.vue'
Vue.component("PartUpload", PartUpload);

Vue.use(ElementUI)
Vue.use(VueRouter)
Vue.use(Vuex)

//处理Token===================================================================================================

var api = {
    toLogin(){
        this.$message({ message: '登录失效,您需要重新登录',type: 'error'});
        localStorage.clear();
        router.replace({ path:"/login" });
    },
    noPermission(){
        this.$message({ message: '您没有访问权限',type: 'error'});
    }
};

//请求头添加Token
axios.interceptors.request.use(config => {
    //如果已经登录了,每次都把token作为一个请求头传递过程
    if (localStorage.getItem('U-TOKEN')) {
        // 让每个请求携带token--['X-Token']为自定义key 请根据实际情况自行修改
        config.headers['Authorization'] = "Bearer "+localStorage.getItem('U-TOKEN')
    }
    return config
}, error => {
    Promise.reject(error)
})

//后置拦截器,处理登录过期
axios.interceptors.response.use(config => {
    return config
},error => {
    if (error && error.response) {
        if( error.response.status == 401 &&
            error.response.data &&
            error.response.data.error_description &&
            error.response.data.error_description.indexOf("Access token expired")){
            return api.toLogin();
        }else if(error.response.status == 403){
            return api.noPermission();
        }
    }
    Promise.reject(error)
});

//处理路由
const router = new VueRouter({
  routes
});

//检查是否登录
router.beforeEach((to, from, next) => {

  if (to.path == '/login') {
    //重新登录,把原来session移除掉
    localStorage.removeItem('user');
    localStorage.removeItem('U-TOKEN');
    localStorage.removeItem('R-TOKEN');
    localStorage.removeItem('expiresTime');
  }

  //从session获取用户
  let user = JSON.parse(localStorage.getItem('user'));
  if (!user &&(to.path != '/login' && to.path != '/register') ) {
    //没有获取到,跳转登录路由地址
    next({ path: '/login' })
  } else {
    //已经登录,正常访问
    next()
  }
})


new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')
